package com.ulife.permission.module.action;

import static com.alibaba.citrus.turbine.util.TurbineUtil.getTurbineRunData;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.citrus.service.form.Group;
import com.alibaba.citrus.turbine.Context;
import com.alibaba.citrus.turbine.Navigator;
import com.alibaba.citrus.turbine.dataresolver.FormGroup;
import com.alibaba.citrus.turbine.support.TurbineRunDataImpl;
import com.alibaba.citrus.webx.WebxException;
import com.ulife.common.GroupUtils;
import com.ulife.common.Result;
import com.ulife.common.WebConstant;
import com.ulife.common.exception.ManagerException;
import com.ulife.permission.common.SysUser;
import com.ulife.permission.common.TargetEnum;
import com.ulife.permission.dao.dataobject.RoleDO;
import com.ulife.permission.dao.dataobject.UserDO;
import com.ulife.permission.manager.RoleManager;
import com.ulife.permission.manager.UserManager;
import com.ulife.permission.module.vo.UserVO;

public class LoginAction {
	private static final Logger log = LoggerFactory.getLogger(LoginAction.class);
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private UserManager userManager;
	
	@Autowired
	private RoleManager roleManager;

	public void doLogin(@FormGroup("login") Group group, Context context, Navigator nav) throws WebxException {
		TurbineRunDataImpl rundata = (TurbineRunDataImpl)getTurbineRunData(request);
		GroupUtils groupUtil = new GroupUtils(group);
		String userName = groupUtil.getString("userName");
		String password = groupUtil.getString("password");
		
		try {
			SysUser sysUser = (SysUser) request.getSession().getAttribute(WebConstant.SYS_USER_SESSION_KEY);
			if (sysUser != null && sysUser.hasLoggedIn()) {
				context.put("error", "您已登录");
				nav.forwardTo("error");
				return;
			}
			Result<UserDO> result = userManager.login(userName, password);
			if (!result.isSuccess() || null == result.getModule()) {
				groupUtil.setMessage("loginError", "invalidUserOrPassword");
				return;
			}
			UserDO user = result.getModule();
			sysUser = new SysUser(user.getUserId(), user.getUserName(), user.getDepartment());
			request.getSession().setAttribute(WebConstant.SYS_USER_SESSION_KEY, sysUser);
			UserVO userVO = new UserVO();
			BeanUtils.copyProperties(user, userVO);
			context.put("user", userVO);
			context.put("sysUser", sysUser);
			context.put("hasLoggedIn", true);
			String userRoleStr = user.getRoleIdList();
			if (StringUtils.equals(userRoleStr, "admin")) {
				putAllPermission(rundata);
			}else {
				String[] userRoles = StringUtils.split(userRoleStr, ",");
				List<String> userList = new ArrayList<String>();
				CollectionUtils.addAll(userList, userRoles);
				dealPermission(userList, rundata);
			}
			nav.forwardTo("home");
		} catch (Exception e) {
			log.error("login error, user name = " + userName, e);
		}
	}
	
	private void putAllPermission(TurbineRunDataImpl rundata) {
		for(TargetEnum p : TargetEnum.values()) {
			rundata.getContext().put(p.getTarget(), p.getTarget());
		}
	}

	private void dealPermission(List<String> userList, TurbineRunDataImpl rundata) {
		if (CollectionUtils.isNotEmpty(userList)) {
			for (String rIdStr : userList) {
				long rId = Long.parseLong(rIdStr);
				try {
					Result<RoleDO> roleResult = roleManager.getRoleById(rId);
					if (roleResult != null && roleResult.isSuccess() && roleResult.getModule() != null) {
						RoleDO role = roleResult.getModule();
						String targetListStr = role.getTargetList();
						String functionListStr = role.getFunctionList();
						String[] targets = StringUtils.split(targetListStr, ",");
						String[] functions = StringUtils.split(functionListStr, ",");
						if (targets != null) {
							for (String t : targets) {
								rundata.getContext().put(t, t);
							}
						}
						if (functions != null) {
							for (String f : functions) {
								rundata.getContext().put(f, f);
							}
						}
					}
				} catch (ManagerException e) {
					log.error("get role by role id error, role id = " + rId, e);
				}
			}
		}
	}
}
